//
//  AppDelegate.m
//  ios-supplier
//
//  Created by feynmanyuan on 15/4/15.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import <AudioToolbox/AudioToolbox.h>
#import <CoreFoundation/CoreFoundation.h>
#import "AppDelegate.h"
#import "JFBGlobalSetting.h"
#import "MiPushSDK.h"
#import "JFBStoreInfoDS.h"
#import "Reachability.h"
#import <dlfcn.h>
#import "APService.h"
#import "YTKNetworkConfig.h"

@interface AppDelegate ()<MiPushSDKDelegate, UIApplicationDelegate, UIAlertViewDelegate> {
    Reachability * hostReach;
    NSString * currentUpdateURL;
}
@property (nonatomic) BOOL isLaunchedByNotification;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [YTKNetworkConfig sharedInstance].baseUrl = API_HOST;
    //网络连接的判断
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];
    hostReach = [Reachability reachabilityForInternetConnection];
    if (hostReach.currentReachabilityStatus != NotReachable){
        self.isNetworkReachable = YES;
    } else {
        self.isNetworkReachable = NO;
        CCAlert(nil, @"您的设备似乎已断开与互联网的连接");
    }
    [hostReach startNotifier];
    
    // Override point for customization after application launch.
    [self customizeAppearance];
    
    // 注册APN
    [self registerForRemoteNotifications];
    
    //集成jpush
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                       UIUserNotificationTypeSound |
                                                       UIUserNotificationTypeAlert)
                                           categories:nil];
    } else {
        //categories 必须为nil
        [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                       UIRemoteNotificationTypeSound |
                                                       UIRemoteNotificationTypeAlert)
                                           categories:nil];
    }
    
    
    [APService setupWithOption:launchOptions];
    NSDictionary *remoteNotification = [launchOptions objectForKey:kJPFNetworkDidReceiveMessageNotification];
    if (remoteNotification != nil) {
        self.isLaunchedByNotification = YES;
    }else{
        self.isLaunchedByNotification = NO;
    }
    //此处会重复提醒
//    NSDictionary *remoteNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
//    if( remoteNotification ) {
//        [self application:application didReceiveRemoteNotification:remoteNotification];
//    }
    
    // 检查更新
//    [self checkUpdate:false];

//    JFBGlobalSetting * setting = [JFBGlobalSetting getSetting];
//    NSString * token = setting.accessToken;
//    
    // 判断登录跳转页面，顺序流，不做全局登录
    //这里的判断是之前做了登录就不到登录界面
    UIViewController* viewController;
    UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    if (![[NSUserDefaults standardUserDefaults]objectForKey:@"ut"]) {

        viewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"Login"];
    }else{
        viewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"OrderTabarContainer"];
    
    }
   
    self.window.rootViewController = viewController;
    [self.window makeKeyAndVisible];
    
    
    return YES;
}

//- (void)loadReveal
//{
//    if (NSClassFromString(@"IBARevealLoader") == nil)
//    {
//        NSString *revealLibName = @"libReveal";
//        NSString *revealLibExtension = @"dylib";
//        NSString *error;
//        NSString *dyLibPath = [[NSBundle mainBundle] pathForResource:revealLibName ofType:revealLibExtension];
//        
//        if (dyLibPath != nil)
//        {
//            NSLog(@"Loading dynamic library: %@", dyLibPath);
//            void *revealLib = dlopen([dyLibPath cStringUsingEncoding:NSUTF8StringEncoding], RTLD_NOW);
//            
//            if (revealLib == NULL)
//            {
//                error = [NSString stringWithUTF8String:dlerror()];
//            }
//        }
//        else
//        {
//            error = @"File not found.";
//        }
//        
//        if (error != nil)
//        {
//            NSString *message = [NSString stringWithFormat:@"%@.%@ failed to load with error: %@", revealLibName, revealLibExtension, error];
//            [[[UIAlertView alloc] initWithTitle:@"Reveal library could not be loaded" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
//        }
//    }
//}

- (void)application:(UIApplication *)app
    didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    //极光推送
    [APService registerDeviceToken:deviceToken];
    NSLog(@"绑定设备ID:%@", deviceToken);
    JFBGlobalSetting *setting = [JFBGlobalSetting getSetting];
    //设置别名
    [APService setAlias:[NSString stringWithFormat:@"jfb_shop+%lu",(unsigned long)setting.shopId] callbackSelector:nil object:nil];
    // 注册APNS成功, 注册deviceToken
    [MiPushSDK bindDeviceToken:deviceToken];
    return;
}

- (void)application:(UIApplication *)app
    didFailToRegisterForRemoteNotificationsWithError:(NSError *)err
{
    NSLog(@"APN注册失败%@", err);
}



- (void)miPushRequestSuccWithSelector:(NSString *)selector data:(NSDictionary *)data
{
    NSLog(@"小米Push绑定成功:%@, %@", data, selector);
    JFBGlobalSetting *setting = [JFBGlobalSetting getSetting];
    
    //如果登录则在服务器注册
    if( setting.isLogin ) {
        NSString *alias = [NSString stringWithFormat:@"jfb_shop_%lu", (unsigned long)setting.shopId];
        if( [selector isEqualToString:@"bindDeviceToken:"] ) {
            [MiPushSDK setAlias: alias];
            
            // 本地存储
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:[data objectForKey:@"token"] forKey:DeviceTokenStringKEY];
            [userDefaults setBool:YES forKey:DeviceTokenRegisteredKEY];
            
            [JFBStoreInfoDS registerDevice:^(BOOL isSuccess, NSString *message, NSError *error) {
                
                NSLog(@"别名注册:%@", alias);
            } pushId:[NSString stringWithFormat:@"%@",[data objectForKey:@"regid"]]];
            
        }
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
//    [self application:application didReceiveRemoteNotification:userInfo];
//    completionHandler(UIBackgroundFetchResultNoData);
}
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    [APService showLocalNotificationAtFront:notification identifierKey:nil];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [APService handleRemoteNotification:userInfo];
    NSLog(@"Test 推送:%@", userInfo);
    [self playTips];
}

-(NSString*)convertVersion{
    NSDictionary * infoDict =[[NSBundle mainBundle] infoDictionary];
    NSString * currentVersion =[infoDict objectForKey:@"CFBundleVersion"];
    
    NSArray *versionArr = [currentVersion componentsSeparatedByString:@"."];
    
    NSMutableArray *version = [@[] mutableCopy];
    
    for( NSString * ver in versionArr ) {
        [version addObject:[NSString stringWithFormat:@"%02d",  [ver intValue]]];
    }
    
    return [NSString  stringWithFormat:@"%d", [[version componentsJoinedByString:@""] intValue]];
}

-(void)playTips{
    JFBGlobalSetting * setting = [JFBGlobalSetting getSetting];
    if([[setting getSettingInfo:@"alertSound"] boolValue]) {
        SystemSoundID soundID ;
        // 获取音效文件的url
        NSURL *url = [[NSBundle mainBundle] URLForResource:@"ring.mp3" withExtension:nil];
        // 根据url创建
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundID);
        AudioServicesPlaySystemSound(soundID);
    } else {
        AudioServicesPlaySystemSound(1012);
    }
}

//-(void)checkUpdate:(BOOL)isTips{
//    NSString * currentVersion = [self convertVersion];
//    [JFBStoreInfoDS checkVersion:^(BOOL isSuccess, NSString *message, NSString *updateURL, NSError *error) {
//        if( isSuccess ) {
//            currentUpdateURL = updateURL;
//            UIAlertView *alert = [[UIAlertView alloc]
//                                  initWithTitle:@"版本更新"
//                                  message:message
//                                  delegate:self
//                                  cancelButtonTitle:@"前往更新"
//                                  otherButtonTitles:@"取消",nil];
//            [alert show];
//        } else {
//            if( isTips ) {
//                UIAlertView *alert = [[UIAlertView alloc]
//                                      initWithTitle:@"版本更新"
//                                      message:@"目前没有更新版本"
//                                      delegate:nil
//                                      cancelButtonTitle:@"确定"
//                                      otherButtonTitles:nil,nil];
//                [alert show];
//            }
//        }
//    } currentVersion:currentVersion];
//}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if( buttonIndex == 0 ) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:currentUpdateURL]];
    }
}

- (void)miPushRequestErrWithSelector:(NSString *)selector error:(int)error data:(NSDictionary *)data
{
    NSLog(@"请求失败:%@,%d", data, error);
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];

}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskPortrait;
}

- (void)customizeAppearance {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    // Set Navigation的标题样式
    NSDictionary * navigationTitleTextAttribute = @{NSForegroundColorAttributeName: UIColorFromRGB(ApplicationTitleColor), NSFontAttributeName:[UIFont boldSystemFontOfSize:18]};
    [[UINavigationBar appearance] setTitleTextAttributes:navigationTitleTextAttribute];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [[UIBarButtonItem appearance] setTintColor:[UIColor whiteColor]];
    // TODO:
    NSDictionary * navigationBarButtomItemTextAttribute = @{NSForegroundColorAttributeName: UIColorFromRGB(ApplicationTitleColor), NSFontAttributeName:[UIFont boldSystemFontOfSize:14]};
    [[UIBarButtonItem appearance] setTitleTextAttributes:navigationBarButtomItemTextAttribute forState:UIControlStateNormal|UIControlStateSelected];
    [[UITextField appearance] setTintColor:TextColorImportButton];
    
    //设置segment样式
    UIImage * segmentSelected = [[UIImage imageNamed:@"barsegment_on.png"] resizableImageWithCapInsets:UIEdgeInsetsZero resizingMode:UIImageResizingModeStretch];
    UIImage * segmentNormal = [[UIImage imageNamed:@"barsegment_off.png"] resizableImageWithCapInsets:UIEdgeInsetsZero resizingMode:UIImageResizingModeStretch];
    UIImage * segmentLine = [[UIImage imageNamed:@"barsegment_off.png"] resizableImageWithCapInsets:UIEdgeInsetsZero resizingMode:UIImageResizingModeStretch];
    //    [XCUtil imageWithColor:[UIColor whiteColor] size:CGSizeZero];
    [[UISegmentedControl appearance] setBackgroundImage:segmentNormal forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [[UISegmentedControl appearance] setBackgroundImage:segmentSelected forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
//    [[UISegmentedControl appearance] setBackgroundImage:segmentSelected forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
    [[UISegmentedControl appearance] setBackgroundImage:segmentSelected forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
    [[UISegmentedControl appearance] setDividerImage:segmentLine forLeftSegmentState:UIControlStateSelected rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [[UISegmentedControl appearance] setDividerImage:segmentLine forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
    [[UISegmentedControl appearance] setDividerImage:segmentLine forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    
    
    NSDictionary * textAttibutesSelected = @{NSForegroundColorAttributeName: TextColorDefault, NSFontAttributeName:[UIFont boldSystemFontOfSize:14]};
    
    NSDictionary * textAttibutesUnSelected = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:14], NSForegroundColorAttributeName:TextColorLight};
    
    
    [[UISegmentedControl appearance] setTitleTextAttributes:textAttibutesSelected forState:UIControlStateSelected];
    [[UISegmentedControl appearance] setTitleTextAttributes:textAttibutesUnSelected forState:UIControlStateNormal];
    
    [[UITabBar appearance] setTintColor:ApplicationColor];
    [[UITabBar appearance] setBarTintColor:TabarPanelColor];
}



// token相关
-( void )registerForRemoteNotifications{
//    if (IS_OS_8_OR_LATER) {
//        [[UIApplication sharedApplication] registerForRemoteNotifications];
//        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes: (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound) categories:nil];
//        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
//    } else {
//        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
//         UIRemoteNotificationTypeBadge |
//         UIRemoteNotificationTypeAlert |
//         UIRemoteNotificationTypeSound];
//    }
    JFBGlobalSetting *setting = [JFBGlobalSetting getSetting];
    if( setting.isLogin ){
        [MiPushSDK registerMiPush:self];
    }
}

- (void)reachabilityChanged:(NSNotification*)note{
    Reachability* curReach= [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    NetworkStatus status= [curReach currentReachabilityStatus];
    if(status == NotReachable) {
        self.isNetworkReachable = NO;
        CCAlert(nil, @"您的设备似乎已断开与互联网的连接");
    }else if (status == ReachableViaWWAN){
        self.isNetworkReachable = YES;
    }else if (status == ReachableViaWiFi){
        self.isNetworkReachable = YES;
    }
}

@end
